package com.azh.server.transport;

import java.nio.charset.StandardCharsets;
import java.util.Arrays;

import com.google.common.primitives.Bytes;

/**
 * @author zhaozhenhang <zhaozhenhang@kuaishou.com>
 * Created on 2022-05-02
 * Encoder编码package为字节数组，对方接收后解码成package对象，编解码规则如下
 * [FLag][data]
 * 如果flag为1，则说明发送错误消息，如果flag为0，则发送正常数据
 */
public class Encoder {

    public byte[] encode(Package pkg) {
        if (pkg.getErr() != null) {
            Exception err = pkg.getErr();
            String msg = "Intern server error";
            if (err.getMessage() != null) {
                msg = err.getMessage();
            }
            return Bytes.concat(new byte[] {1}, msg.getBytes(StandardCharsets.UTF_8));
        }
        return Bytes.concat(new byte[] {0}, pkg.getData());
    }

    public Package decode(byte[] data) throws Exception {
        if (data.length < 1) {
            throw new RuntimeException("Intern server error");
        }
        if (data[0] == 0) {
            return new Package(Arrays.copyOfRange(data, 1, data.length), null);
        } else if (data[0] == 1) {
            return new Package(null, new RuntimeException(new String(Arrays.copyOfRange(data, 1, data.length))));
        }
        throw new RuntimeException("Intern server error");
    }
}
